<?php

class XImgUploadAction extends XUploadAction {
    
    public $imagesTable;
    
    protected function beforeReturn() {
        $path = $this->getPath();
        Yii::app()->db->createCommand()->insert($this->imagesTable, array('bigImg'=>$this->formModel->{$this->fileNameAttribute}, 'date'=>time()));
        $userFiles = Yii::app()->user->getState( $this->stateVariable, array());
        $userFiles[$this->formModel->{$this->fileNameAttribute}] = array(
            "path" => $path.$this->formModel->{$this->fileNameAttribute},
            "thumb" => $path.$this->formModel->{$this->fileNameAttribute},
            "filename" => $this->formModel->{$this->fileNameAttribute},
            'size' => $this->formModel->{$this->sizeAttribute},
            'mime' => $this->formModel->{$this->mimeTypeAttribute},
            'name' => $this->formModel->{$this->displayNameAttribute},
            'fileId' => Yii::app()->db->lastInsertID,
        );    
        Yii::app()->user->setState('xuploadFiles', $userFiles);
        return true;
    }
    
    protected function handleDeleting() {
        if (isset($_GET["_method"]) && $_GET["_method"] == "delete") {
            $success = false;
            if ($_GET["file"][0] !== '.' && Yii::app()->user->hasState($this->stateVariable)) {
                $userFiles = Yii::app()->user->getState($this->stateVariable, array());
                if (!empty($userFiles) && $this->fileExists($userFiles[$_GET["file"]])) {
                    $success = $this->deleteFile($userFiles[$_GET["file"]]);
                    if ($success) {
                        Yii::app()->db->createCommand()->delete($this->imagesTable, 'imgId=:id', array(':id'=>$userFiles[$_GET["file"]]['fileId']));
                        unset($userFiles[$_GET["file"]]); 
                        Yii::app()->user->setState($this->stateVariable, $userFiles);
                    }
                }
            }
            echo json_encode($success);
            return true;
        }
        return false;
    }
}